use tauri::menu::{MenuBuilder, MenuItemBuilder};
use tauri::tray::TrayIconBuilder;
use tauri::Manager;
use tauri_plugin_global_shortcut::GlobalShortcutExt;
use tauri_plugin_global_shortcut::{ShortcutState};

// 内嵌默认托盘图标作为备用方案
const TRAY_ICON_FALLBACK: &[u8] = include_bytes!("../icons/32x32.png");

// 业务模块
mod volcengine;
mod config;
mod clipboard;
mod screenshot;
mod window;
mod shortcut;
mod translate;
mod request;

#[cfg(target_os = "macos")]
mod macos_window;

// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#[cfg_attr(not(debug_assertions), windows_subsystem = "windows")]

fn main() {
    tauri::Builder::default()
        .manage(screenshot::ScreenshotCache::new())
        .manage(screenshot::ScreenshotState::new())
        .manage(config::AppConfigStore {
            cfg: std::sync::Mutex::new(config::AppConfig::default()),
        })
        .manage(shortcut::ShortcutStore::new())
        .setup(|app| {
            setup_app(app)?;
            Ok(())
        })
        .invoke_handler(tauri::generate_handler![
            // 翻译模块
            translate::translate,
            // 窗口管理模块
            window::create_translate_window,
            window::create_setting_window,
            window::show_main_window,
            window::close_current_window,
            window::move_window,
            window::read_file_as_base64,
            window::get_current_screen,
            // 截图模块
            screenshot::start_screenshot_overlay,
            screenshot::close_overlay_window,
            screenshot::close_other_overlays,
            screenshot::capture_selected_area,
            screenshot::copy_selected_area_to_clipboard,
            screenshot::capture_from_cache,
            screenshot::copy_from_cache,
            screenshot::pin_selected_area,
            // 配置模块
            config::get_app_config,
            config::set_app_config,
            config::get_screenshot_config,
            config::set_screenshot_config,
            // 快捷键模块
            shortcut::get_shortcuts,
            shortcut::set_shortcuts,
            // 网络请求模块
            request::http_request,
            request::http_get,
            request::http_post,
        ])
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}

/// 应用初始化设置
fn setup_app(app: &mut tauri::App) -> Result<(), Box<dyn std::error::Error>> {
    // 设置为辅助应用模式（不显示在 Dock 和菜单栏）
    #[cfg(target_os = "macos")]
    {
        use macos_window::set_activation_policy_accessory;
        if let Err(e) = set_activation_policy_accessory() {
            eprintln!("设置辅助应用模式失败: {}", e);
        }
    }
    
    // 加载配置
    if let Some(saved) = config::load_config(&app.handle()) {
        let store = app.state::<config::AppConfigStore>();
        let mut cfg = store.cfg.lock().unwrap();
        *cfg = saved;
    }
    
    // 创建系统托盘
    setup_tray(app)?;
    
    // 初始化全局快捷键
    setup_global_shortcuts(app)?;
    
    Ok(())
}

/// 创建系统托盘
fn setup_tray(app: &tauri::App) -> Result<(), Box<dyn std::error::Error>> {
    let label_width = 20;
    let cfg_menu = app.state::<config::AppConfigStore>().cfg.lock().unwrap().shortcut.clone();
    
    let label_translate = format!(
        "{}{}",
        shortcut::pad_label("翻译", label_width),
        shortcut::display_shortcut_str(&cfg_menu.translate)
    );
    let label_screenshot = format!(
        "{}{}",
        shortcut::pad_label("截屏", label_width),
        shortcut::display_shortcut_str(&cfg_menu.screenshot)
    );
    let label_setting = format!(
        "{}{}",
        shortcut::pad_label("偏好设置", label_width),
        shortcut::display_shortcut_str(&cfg_menu.setting)
    );
    let label_quit = shortcut::pad_label("退出", label_width);
    
    let menu_translate = MenuItemBuilder::new(&label_translate)
        .id("translate")
        .build(app)?;
    let menu_screenshot = MenuItemBuilder::new(&label_screenshot)
        .id("screenshot")
        .build(app)?;
    let menu_setting = MenuItemBuilder::new(&label_setting)
        .id("setting")
        .build(app)?;
    let menu_quit = MenuItemBuilder::new(&label_quit).id("quit").build(app)?;

    let menu = MenuBuilder::new(app)
        .item(&menu_translate)
        .item(&menu_screenshot)
        .item(&menu_setting)
        .separator()
        .item(&menu_quit)
        .build()?;

    // 加载托盘图标（先尝试从文件，失败则使用内嵌图标）
    let tray_icon = load_tray_icon(app)
        .or_else(|| load_tray_icon_fallback());

    if let Some(icon) = tray_icon {
        if let Err(e) = TrayIconBuilder::new()
            .icon(icon)
            .menu(&menu)
            .on_menu_event(move |app, event| {
                handle_tray_menu_event(app, event.id().as_ref());
            })
            .build(app)
        {
            eprintln!("❌ 创建系统托盘失败: {}，应用将继续运行", e);
        } else {
            eprintln!("✅ 系统托盘创建成功");
        }
    } else {
        eprintln!("❌ 严重错误: 无法加载任何托盘图标，系统托盘将不可用");
    }
    
    Ok(())
}

/// 加载托盘图标
fn load_tray_icon(app: &tauri::App) -> Option<tauri::image::Image<'static>> {
    let mut icon_paths = Vec::new();
    
    // 优先使用资源目录中的图标（打包后的路径）
    if let Ok(resource_dir) = app.path().resource_dir() {
        eprintln!("资源目录: {:?}", resource_dir);
        icon_paths.push(resource_dir.join("icons/32x32.png"));
        icon_paths.push(resource_dir.join("icons/icon.png"));
        icon_paths.push(resource_dir.join("icons/128x128.png"));
        
        // macOS 特定格式
        #[cfg(target_os = "macos")]
        {
            icon_paths.push(resource_dir.join("icons/icon.icns"));
        }
        
        // Windows 特定格式
        #[cfg(target_os = "windows")]
        {
            icon_paths.push(resource_dir.join("icons/icon.ico"));
        }
    }
    
    // 开发环境的路径
    icon_paths.push(std::path::PathBuf::from("icons/32x32.png"));
    icon_paths.push(std::path::PathBuf::from("icons/icon.png"));
    
    eprintln!("尝试加载托盘图标，共 {} 个路径", icon_paths.len());
    
    for (idx, path) in icon_paths.iter().enumerate() {
        eprintln!("  [{}] 尝试路径: {:?} (存在: {})", idx + 1, path, path.exists());
        
        if path.exists() {
            match tauri::image::Image::from_path(&path) {
                Ok(img) => {
                    eprintln!("✅ 成功加载托盘图标: {:?}", path);
                    return Some(img);
                }
                Err(e) => {
                    eprintln!("❌ 加载图标失败 {:?}: {}", path, e);
                }
            }
        }
    }
    
    eprintln!("⚠️  警告: 未能加载任何托盘图标");
    None
}

/// 加载内嵌的备用托盘图标
fn load_tray_icon_fallback() -> Option<tauri::image::Image<'static>> {
    eprintln!("📦 尝试使用内嵌的备用图标");
    match tauri::image::Image::from_bytes(TRAY_ICON_FALLBACK) {
        Ok(img) => {
            eprintln!("✅ 成功加载内嵌备用图标");
            Some(img)
        }
        Err(e) => {
            eprintln!("❌ 加载内嵌备用图标失败: {}", e);
            None
        }
    }
}

/// 处理托盘菜单事件
fn handle_tray_menu_event(app: &tauri::AppHandle, event_id: &str) {
    match event_id {
        "translate" => {
            let app_handle = app.clone();
            tauri::async_runtime::spawn(async move {
                if let Err(e) = window::create_translate_window(app_handle).await {
                    eprintln!("创建翻译窗口失败: {}", e);
                }
            });
        }
        "screenshot" => {
            let app_handle = app.clone();
            tauri::async_runtime::spawn(async move {
                if let Err(e) = screenshot::start_screenshot_overlay(app_handle).await {
                    eprintln!("启动截屏遮罩失败: {}", e);
                }
            });
        }
        "setting" => {
            let app_handle = app.clone();
            tauri::async_runtime::spawn(async move {
                if let Err(e) = window::create_setting_window(app_handle).await {
                    eprintln!("创建设置窗口失败: {}", e);
                }
            });
        }
        "quit" => {
            std::process::exit(0);
        }
        _ => {}
    }
}

/// 初始化全局快捷键
fn setup_global_shortcuts(app: &tauri::App) -> Result<(), Box<dyn std::error::Error>> {
    let plugin = tauri_plugin_global_shortcut::Builder::new()
        .with_handler(|app, shortcut, event| {
            if event.state == ShortcutState::Pressed {
                handle_global_shortcut(app, shortcut);
            }
        })
        .build();
    app.handle().plugin(plugin)?;

    let cfg = app.state::<config::AppConfigStore>().cfg.lock().unwrap().shortcut.clone();
    
    // 解析快捷键
    let parsed = match (
        shortcut::parse_shortcut(&shortcut::normalize_shortcut_str(&cfg.translate)),
        shortcut::parse_shortcut(&shortcut::normalize_shortcut_str(&cfg.screenshot)),
        shortcut::parse_shortcut(&shortcut::normalize_shortcut_str(&cfg.setting)),
    ) {
        (Ok(translate), Ok(screenshot), Ok(setting)) => {
            shortcut::ParsedShortcuts {
                translate,
                screenshot,
                setting,
            }
        }
        _ => {
            eprintln!("快捷键解析失败，使用默认快捷键");
            shortcut::create_default_shortcuts()
        }
    };
    
    // 保存解析的快捷键
    {
        let shortcut_store = app.state::<shortcut::ShortcutStore>();
        let mut ps = shortcut_store.parsed_shortcuts.lock().unwrap();
        *ps = Some(parsed.clone());
    }
    
    // 注册快捷键
    let mgr = app.global_shortcut();
    if let Err(e) = mgr.register(parsed.translate.clone()) {
        eprintln!("注册翻译快捷键失败: {}", e);
    }
    if let Err(e) = mgr.register(parsed.screenshot.clone()) {
        eprintln!("注册截图快捷键失败: {}", e);
    }
    if let Err(e) = mgr.register(parsed.setting.clone()) {
        eprintln!("注册设置快捷键失败: {}", e);
    }
    
    Ok(())
}

/// 处理全局快捷键事件
fn handle_global_shortcut(app: &tauri::AppHandle, shortcut: &tauri_plugin_global_shortcut::Shortcut) {
    let shortcut_store = app.state::<shortcut::ShortcutStore>();
    let parsed = shortcut_store.parsed_shortcuts.lock().unwrap();
    
    if let Some(ps) = parsed.as_ref() {
        if *shortcut == ps.translate {
            let app_handle = app.clone();
            tauri::async_runtime::spawn(async move {
                let _ = window::create_translate_window(app_handle).await;
            });
        } else if *shortcut == ps.screenshot {
            let app_handle = app.clone();
            tauri::async_runtime::spawn(async move {
                let _ = screenshot::start_screenshot_overlay(app_handle).await;
            });
        } else if *shortcut == ps.setting {
            let app_handle = app.clone();
            tauri::async_runtime::spawn(async move {
                let _ = window::create_setting_window(app_handle).await;
            });
        }
    }
}
